package com.lixiaohan.lushudao.controller;

import com.lixiaohan.lushudao.dao.RoamCommentMapper;
import com.lixiaohan.lushudao.dao.RoamUserInfoMapper;
import com.lixiaohan.lushudao.dao.ScenicReleaseInfoMapper;
import com.lixiaohan.lushudao.pojo.*;
import com.lixiaohan.lushudao.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 景点发布信息评论Controller
 */
@RestController
@RequestMapping("/ScenicComment")
public class RoamCommentController {
    /**
     * 根据景点发布信息的id——srid查询所有的评论
     */
    @RequestMapping("/findAllCommentBySrid")
    public Result findAllCommentBySrid(Integer srid){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        List<RoamComment> roamCommentList;
        try {
            RoamCommentMapper mapper = sqlSession.getMapper(RoamCommentMapper.class);
            roamCommentList = mapper.findAllCommentBySrid(srid);
        } catch (Exception e) {
            return Result.error().message("失败");
        } finally {
            if (sqlSession!=null){
                sqlSession.close();}
        }
        return Result.ok().message("成功").data("roamCommentList",roamCommentList);

    }

    /**
     * 根据用户id——uid查询所有的评论
     */
    @RequestMapping("/findAllCommentByUid")
    public Result findAllCommentByUid(HttpSession session){
        SqlSession sqlSession=null;
        List<RoamComment> roamCommentList;
        try {
            RoamUserInfo usersession = (RoamUserInfo) session.getAttribute("user");
            Integer uid=usersession.getUserId();
            sqlSession = MybatisUtils.getSqlSession();
            RoamCommentMapper mapper = sqlSession.getMapper(RoamCommentMapper.class);
            roamCommentList = mapper.findAllCommentByUid(uid);
            return Result.ok().message("成功").data("roamCommentList",roamCommentList);
        } catch (Exception e) {
            return Result.error().message("服务器出错");
        } finally {
            if (sqlSession!=null){
                sqlSession.close();}
        }

    }


    /**
     * 为景点发布信息添加评论（前端传来三个参数，时间自动生成，点赞数默认为0）
     * @param
     * @return
     */
    @RequestMapping(value = "/addRoamComment",method = RequestMethod.POST)
    public Result addRoamComment(RoamCommentRequest request, HttpSession session, HttpServletResponse httpResponse, HttpServletRequest httpRequest){
        System.out.println(request);
        request.setUid(41);
        System.out.println(request.getUid()+"发布评论了！！"+request);
        SqlSession sqlSession=null;
        try {
            sqlSession = MybatisUtils.getSqlSession();
//            RoamUserInfo usersession = (RoamUserInfo) session.getAttribute("user");
            RoamUserInfoMapper userInfoMapper = sqlSession.getMapper(RoamUserInfoMapper.class);
            RoamUserInfo usersession = userInfoMapper.FindOneUserByUid(request.getUid());
            Integer uid=usersession.getUserId();

            RoamComment roamComment = new RoamComment();

            roamComment.setUserId(uid);
            Date date = new Date();
            Timestamp timestamp=new Timestamp(date.getTime());
            roamComment.setCommentTime(timestamp);
            roamComment.setCommentContent(request.getContent());
            roamComment.setCommentGood(0);
            roamComment.setScenicReleaseId(request.getSrid());

            sqlSession = MybatisUtils.getSqlSession();
            RoamCommentMapper mapper = sqlSession.getMapper(RoamCommentMapper.class);
            Integer integer = mapper.addOneComment(roamComment);
            if (integer==1){
                System.out.println("成功了");
                System.out.println("渲染视图");
                sqlSession = MybatisUtils.getSqlSession();
                ScenicReleaseInfoMapper srMapper = sqlSession.getMapper(ScenicReleaseInfoMapper.class);
                ScenicReleaseInfo scenicReleaseInfo = srMapper.findOneBySrid(request.getSrid());
                RoamCommentMapper commentMapper = sqlSession.getMapper(RoamCommentMapper.class);
                if (scenicReleaseInfo != null) {
                    String srTitle = scenicReleaseInfo.getScenicReleaseTitle();//景点标题
                    String srText = scenicReleaseInfo.getScenicReleaseText();//景点信息内容
                    Timestamp spaceReleaseTime = scenicReleaseInfo.getSpaceReleaseTime();
                    String srTime = spaceReleaseTime.toString();//景点发布时间
                    Integer userId = scenicReleaseInfo.getUserId();
                    RoamUserInfo userInfo = userInfoMapper.FindOneUserByUid(userId);
                    String headUrl = userInfo.getUserHead();
            /*
            评论
             */
                    List<RoamComment> commentList = commentMapper.findAllCommentBySrid(request.getSrid());
                    List<Map<String, Object>> commentDetailList = commentList.stream()
                            .sorted(Comparator.comparing(RoamComment::getCommentId).reversed())
                            .map(commentItem -> {
                        Map<String, Object> commentDetailMap = new HashMap<>();
                        Integer commentUserId = commentItem.getUserId();
                        RoamUserInfo commentUserInfo = userInfoMapper.FindOneUserByUid(commentUserId);
                        commentDetailMap.put("commentInfo", commentItem);
                        commentDetailMap.put("commentUserInfo", commentUserInfo);
                        return commentDetailMap;
                    }).collect(Collectors.toList());

                    System.out.println("commentDetailList-add:");
                    System.out.println(commentDetailList);
//                    session.setAttribute("title", srTitle);
//                    session.setAttribute("text", srText);
//                    session.setAttribute("time", srTime);
//                    session.setAttribute("headUrl", headUrl);
//                    session.setAttribute("userName", userInfo.getUserName());
//                    session.setAttribute("commentDetailList", commentDetailList);
//                    session.setAttribute("srid",request.getSrid());
                    return Result.ok().data("commentDetailList",commentDetailList);
                }
            }
            return Result.error();
        }catch (Exception e){
            return Result.error();
        }
        finally {
            if (sqlSession!=null){
                sqlSession.close();
            }
        }

    }

}
